package com.ibeeking.found.common.resolver;

import cn.hutool.core.util.StrUtil;
import com.ibeeking.found.common.constants.HeaderNounConstant;
import com.ibeeking.found.common.annotation.LoginUser;
import com.ibeeking.found.common.entity.CurrentUser;
import com.ibeeking.nematos.exception.AuthorizationException;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 封装当前登录用户信息
 *
 * @Author ibeeking
 * @date 2020/10/21
 */
public class RequestUserResolver implements HandlerMethodArgumentResolver {

    /**
     * 入参筛选
     *
     * @param methodParameter 参数集合
     * @return 格式化后的参数
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(LoginUser.class) && methodParameter.getParameterType().equals(CurrentUser.class);
    }

    /**
     * @param methodParameter       入参集合
     * @param modelAndViewContainer model 和 view
     * @param nativeWebRequest      web相关
     * @param webDataBinderFactory  入参解析
     * @return 包装对象
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String userId = request.getHeader(HeaderNounConstant.USER_ID);
        String userName = request.getHeader(HeaderNounConstant.USER_NAME);
        String tenantIndustry = request.getHeader(HeaderNounConstant.INDUSTRY);
        if (StrUtil.isBlank(userId)) {
            throw new AuthorizationException("resolveArgument error userId is empty");
        }
        if (StrUtil.isBlank(userName)) {
            userName = "";
        }
        CurrentUser currentUser = new CurrentUser();
        currentUser.setId(Long.valueOf(userId));
        currentUser.setName(userName);
        currentUser.setIndustry(tenantIndustry);
        return currentUser;
    }
}
